package com.sp.business.objectmodel;

import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.sp.generated.xml.firemon.BooleanProperty;
import com.sp.generated.xml.firemon.IntegerProperty;
import com.sp.generated.xml.firemon.StringProperty;

public class NormalizedData
{
  private static final String inescabableXmlCharactersPatternText = "[^\u0009\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF\r\n]+";
  private static final Pattern inescabableXmlCharactersPattern = Pattern.compile(inescabableXmlCharactersPatternText,
      Pattern.MULTILINE | Pattern.UNIX_LINES);

  public static String removeInescapableXmlCharacters(String text)
  {
    return inescabableXmlCharactersPattern.matcher(text).replaceAll("");
  }

  public static StringProperty createStringProperty(String value)
  {
    return createStringProperty(null, value);
  }

  public static StringProperty createStringProperty(String name, String value)
  {
    StringProperty property = new StringProperty();
    property.setName(name);

    if (value != null)
    {
      value = removeInescapableXmlCharacters(value);
    }

    property.setValue(value);

    return property;
  }

  public static BooleanProperty createBooleanProperty(boolean value)
  {
    return createBooleanProperty(null, value);
  }

  public static BooleanProperty createBooleanProperty(String name, boolean value)
  {
    BooleanProperty property = new BooleanProperty();
    property.setName(name);
    property.setValue(value);

    return property;
  }

  public static IntegerProperty createIntegerProperty(Integer value)
  {
    return createIntegerProperty(null, value);
  }

  public static IntegerProperty createIntegerProperty(String value)
  {
    if (StringUtils.isBlank(value))
    {
      return null;
    }

    return createIntegerProperty(null, value);
  }

  public static IntegerProperty createIntegerProperty(String name, String valueText)
  {
    Integer value = null;

    try
    {
      value = Integer.valueOf(valueText);
    }
    catch (NumberFormatException ex)
    {
    }

    return createIntegerProperty(name, value);
  }

  public static IntegerProperty createIntegerProperty(String name, Integer value)
  {
    IntegerProperty property = new IntegerProperty();
    property.setName(name);
    property.setValue(value);

    return property;
  }

}
